package com.iring.util.proxy;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.util.Assert;

import com.iring.domain.config.prop.SIPProperties;


/**
 * sip http 接口工具
 *
 * @author wanggan
 */

@Configuration
@ConditionalOnBean({ SIPProperties.class, HttpComponentsClientHttpRequestFactory.class })
public class ProxyHttpUtil {

    private static final Logger logger = LoggerFactory.getLogger(ProxyHttpUtil.class);

    @Autowired
    private HttpComponentsClientHttpRequestFactory httpRequestFactory;

    @Autowired
    private SIPProperties sipProperties;

    public String sendData(String path, HttpMethod httpMethod) throws Exception {
        String url = sipProperties.getSipUrl();

        logger.info("request proxy url={}", url + path);
        logger.info("request proxy method={}", httpMethod);
        StringBuilder sb = new StringBuilder();
        ClientHttpResponse httpResponse = null;
        try {
            URI uri = new URI(url + path);
            Assert.notNull(httpRequestFactory, "'httpRequestFactory' must not be null");
            ClientHttpRequest httpRequest = httpRequestFactory.createRequest(uri, httpMethod);

            HttpHeaders headers = httpRequest.getHeaders();
            headers.set("Content-Type", "application/json;charset=UTF-8");
            httpResponse = httpRequest.execute();
            BufferedReader br = new BufferedReader(new InputStreamReader(httpResponse.getBody()));
            br.lines()
                    .forEach((line) -> {
                        sb.append(line);
                    });
        } catch (URISyntaxException uriSyntaxException) {
            logger.info("URISyntaxException...");
        } catch (IOException ioExp) {
            logger.info("IOException={}", ioExp.getMessage());
        } finally {
            if(httpResponse.getStatusCode() != HttpStatus.OK){
                logger.info("bad request={}",sb.toString());
                throw new Exception(sb.toString());
            }
            if (httpResponse != null) {
                httpResponse.close();
            }
        }
        return sb.toString();
    }

}
